﻿@* @page "" *@
@{
    var serverUrl = $"{Context.Request.Scheme}://{Context.Request.Host}";
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Elsa Workflows</title>
    <link rel="icon" type="image/png" sizes="32x32" href="/_content/Elsa.Designer.Components.Web/elsa-workflows-studio/assets/images/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/_content/Elsa.Designer.Components.Web/elsa-workflows-studio/assets/images/favicon-16x16.png">
    <link rel="stylesheet" href="/_content/Elsa.Designer.Components.Web/elsa-workflows-studio/assets/fonts/inter/inter.css">
    <link rel="stylesheet" href="/_content/Elsa.Designer.Components.Web/elsa-workflows-studio/elsa-workflows-studio.css">
    <script src="/_content/Elsa.Designer.Components.Web/monaco-editor/min/vs/loader.js"></script>
    <script type="module" src="/_content/Elsa.Designer.Components.Web/elsa-workflows-studio/elsa-workflows-studio.esm.js"></script>
</head>
<body>
    <elsa-studio-root server-url="@serverUrl" monaco-lib-path="_content/Elsa.Designer.Components.Web/monaco-editor/min">
        <elsa-studio-dashboard culture="zh-CN"></elsa-studio-dashboard>
    </elsa-studio-root>
    <script>
        // 监听message事件
        var messageType = "token";
        window.addEventListener('message', function (event) {
            // 接收并处理token
            if (event.data && event.data.messageType === messageType) {
                localStorage.setItem("accessToken", event.data.accessToken);
                localStorage.setItem("refreshToken", event.data.refreshToken);
            }
        }, false);
    </script>
    <script>
        const refreshTokenUrl = '/api/Login/RefreshLogin';
        const elsaStudioRoot = document.querySelector('elsa-studio-root');

        elsaStudioRoot.addEventListener('initializing', e => {
            const elsaStudio = e.detail;
            elsaStudio.pluginManager.registerPlugin(AuthorizationMiddlewarePlugin);
        });

        function AuthorizationMiddlewarePlugin(elsaStudio) {
            const eventBus = elsaStudio.eventBus;

            eventBus.on('http-client-created', e => {
                // Register Axios middleware.
                // 假设e.service是一个Axios实例或者能够返回Axios实例的对象
                axiosInstance = e.service; // 如果e.service不提供实例，则创建一个新的

                const httpClient = e.service.register({
                    onRequest(request) {
                        request.headers['workflow'] = true;
                        if (request.url === refreshTokenUrl) {
                            request.headers['Authorization'] = localStorage.getItem("refreshToken");
                        } else {
                            request.headers['Content-Type'] = "application/json, text/plain, */*";
                            request.headers['Authorization'] = localStorage.getItem("accessToken");
                        }
                        return request;
                    },
                    onResponse(res) {
                        if (res.config.url === "v1/activities") {
                            res.data = translateWorkflow(res.data);
                        }
                        return res;
                    },
                    onResponseError(error) {
                        const { status, data, statusText } = error.response;
                        if (status === 401) { 
                            if(data){
                                const body = JSON.parse(data);
                                if (body.status === 4000) {
                                    //需要刷新token
                                    return refreshLogin(error);
                                }
                            }
                        }
                    }
                });
            });
        }

        //刷新token
        function refreshLogin(error) {
            return axiosInstance.http.get(refreshTokenUrl).then(res => {
                const { status, data, statusText } = res;
                if (status === 200) {
                    const accessToken = data.data.accessToken;
                    const refreshToken = data.data.refreshToken;
                    // 使用postMessage将新token发送回父页面
                    window.parent.postMessage({ messageType: messageType, accessToken: accessToken, refreshToken: refreshToken }, "*");
                    localStorage.setItem("accessToken", "Bearer " + accessToken);
                    localStorage.setItem("refreshToken", "Bearer " + refreshToken);
                    return axiosInstance.http(error.config);
                }
                return res;
            });
           
        }

        function translateWorkflow(txt) {
            if (txt == null) {
                return "";
            }
            var rv = txt
            .replaceAll("\"displayName\":\"Read Line\"", "\"displayName\":\"读取\"")
            .replaceAll("\"description\":\"Read text from standard in.\"", "\"description\":\"从标准输入中读取\"")
            .replaceAll("\"category\":\"Console\"", "\"category\":\"命令行\"")
            .replaceAll("\"displayName\":\"Write Line\"", "\"displayName\":\"写入\"")
            .replaceAll("\"description\":\"Write text to standard out.\"", "\"description\":\"向标准输出写入\"")
            .replaceAll("\"label\":\"Text\"", "\"label\":\"文本\"")
            .replaceAll("\"hint\":\"The text to write.\"", "\"hint\":\"要写入的文本\"")
            .replaceAll("\"label\":\"Script\"", "\"label\":\"脚本\"")
            .replaceAll("\"hint\":\"The JavaScript to run.\"", "\"hint\":\"要运行的Javascript脚本\"")
            .replaceAll("\"label\":\"Possible Outcomes\"", "\"label\":\"可能的输出\"")
            .replaceAll("\"hint\":\"The possible outcomes that can be set by the script.\"", "\"hint\":\"脚本可能设置的输出\"")
            .replaceAll("\"displayName\":\"HTTP Endpoint\"", "\"displayName\":\"HTTP 端点\"")
            .replaceAll("\"description\":\"Handle an incoming HTTP request.\"", "\"description\":\"处理HTTP请求\"")
            .replaceAll("\"label\":\"Path\"", "\"label\":\"路径\"")
            .replaceAll("\"hint\":\"The relative path that triggers this activity.\"", "\"hint\":\"触发动作的相对路径\"")
            .replaceAll("\"label\":\"Methods\"", "\"label\":\"请求方式\"")
            .replaceAll("\"label\":\"Read Content\"", "\"label\":\"读取内容\"")
            .replaceAll("\"label\":\"Target Type\"", "\"label\":\"目标类型\"")
            .replaceAll("\"displayName\":\"HTTP Response\"", "\"displayName\":\"HTTP 输出\"")
            .replaceAll("\"description\":\"Write an HTTP response.\"", "\"description\":\"输出HTTP内容\"")
            .replaceAll("\"label\":\"Status Code\"", "\"label\":\"状态码\"")
            .replaceAll("\"label\":\"Content\"", "\"label\":\"内容\"")
            .replaceAll("\"displayName\":\"Send HTTP Request\"", "\"displayName\":\"发送Http请求\"")
            .replaceAll("\"description\":\"Send an HTTP request.\"", "\"description\":\"送Http请求\"")
            .replaceAll("\"displayName\":\"Redirect\"", "\"displayName\":\"重定向\"")
            .replaceAll("\"description\":\"Write an HTTP redirect response.\"", "\"description\":\"重定向Http请求\"")
            .replaceAll("\"displayName\":\"Send Email\"", "\"displayName\":\"发送Email\"")
            .replaceAll("\"description\":\"Send an email message.\"", "\"description\":\"发送电子邮件\"")
            .replaceAll("\"category\":\"Timers\"", "\"category\":\"定时\"")
            .replaceAll("\"displayName\":\"Timer\"", "\"displayName\":\"定时器\"")
            .replaceAll("\"description\":\"Triggers at a specified interval.\"", "\"description\":\"指定时间间隔触发\"")
            .replaceAll("\"displayName\":\"Start at\"", "\"displayName\":\"开始\"")
            .replaceAll("\"description\":\"Triggers at a specified moment in time.\"", "\"description\":\"指定时间开始\"")
            .replaceAll("\"displayName\":\"Clear Timer\"", "\"displayName\":\"清除定时器\"")
            .replaceAll("\"description\":\"Cancel a timer (Cron, StartAt, Timer) so that it is not executed.\"", "\"description\":\"清除一个定时器\"")
            .replaceAll("\"category\":\"Workflows\"", "\"category\":\"工作流\"")
            .replaceAll("\"displayName\":\"Run Workflow\"", "\"displayName\":\"运行子流程\"")
            .replaceAll("\"description\":\"Runs a child workflow.\"", "\"description\":\"运行一个子流程\"")
            .replaceAll("\"category\":\"Miscellaneous\"", "\"category\":\"其他\"")
            .replaceAll("\"displayName\":\"Workflow\"", "\"displayName\":\"流程\"")
            .replaceAll("\"category\":\"State Machine\"", "\"category\":\"状态机\"")
            .replaceAll("\"displayName\":\"State\"", "\"displayName\":\"状态\"")
            .replaceAll("\"description\":\"Puts the workflow into the specified state.\"", "\"description\":\"给流程设置状态\"")
            .replaceAll("\"displayName\":\"Interrupt Trigger\"", "\"displayName\":\"中断触发器\"")
            .replaceAll("\"description\":\"Resumes suspended workflows that are blocked on a specific trigger.\"", "\"description\":\"继续一个被某个触发器中断的流程\"")
            .replaceAll("\"displayName\":\"Send Signal\"", "\"displayName\":\"发送信号\"")
            .replaceAll("\"description\":\"Sends the specified signal.\"", "\"description\":\"发送一个信号\"")
            .replaceAll("\"displayName\":\"Signal Received\"", "\"displayName\":\"接收信号\"")
            .replaceAll("\"description\":\"Suspend workflow execution until the specified signal is received.\"", "\"description\":\"暂停工作流直到接收到某个信号\"")
            .replaceAll("\"displayName\":\"Fault\"", "\"displayName\":\"失败\"")
            .replaceAll("\"description\":\"Put the workflow in a faulted state.\"", "\"description\":\"将工作流标记为失败\"")
            .replaceAll("\"displayName\":\"Inline\"", "\"displayName\":\"内联\"")
            .replaceAll("\"category\":\"Primitives\"", "\"category\":\"底层\"")
            .replaceAll("\"displayName\":\"Set Context ID\"", "\"displayName\":\"设置上下文ID\"")
            .replaceAll("\"description\":\"Set context ID on the workflow.\"", "\"description\":\"设置工作流的上下文ID\"")
            .replaceAll("\"displayName\":\"Set Name\"", "\"displayName\":\"设置名称\"")
            .replaceAll("\"description\":\"Set the name of the workflow instance.\"", "\"description\":\"设置工作流实例的名称\"")
            .replaceAll("\"displayName\":\"Set Transient Variable\"", "\"displayName\":\"设置临时变量\"")
            .replaceAll("\"description\":\"Set a transient variable on the current workflow execution context.\"", "\"description\":\"设置一个当前运行流程内的临时变量\"")
            .replaceAll("\"displayName\":\"Set Variable\"", "\"displayName\":\"设置变量\"")
            .replaceAll("\"description\":\"Set variable on the workflow.\"", "\"description\":\"设置流程变量\"")
            .replaceAll("\"displayName\":\"Correlate\"", "\"displayName\":\"关联ID\"")
            .replaceAll("\"description\":\"Set the CorrelationId of the workflow to a given value.\"", "\"description\":\"设置流程的关联ID\"")
            .replaceAll("\"description\":\"Triggers periodically based on a specified CRON expression.\"", "\"description\":\"使用CRON表达式触发\"")
            .replaceAll("\"category\":\"Control Flow\"", "\"category\":\"控制流\"")
            .replaceAll("\"description\":\"Break out of a While, For or ForEach loop.\"", "\"description\":\"中断While, For 或者 ForEach 循环\"")
            .replaceAll("\"displayName\":\"Finish\"", "\"displayName\":\"结束\"")
            .replaceAll("\"description\":\"Removes any blocking activities from the current container (workflow or composite activity).\"", "\"description\":\"取消所有暂停的动作，标记流程结束\"")
            .replaceAll("\"description\":\"Iterate between two numbers.\"", "\"description\":\"在两个数字之间循环\"")
            .replaceAll("\"description\":\"Iterate over a collection.\"", "\"description\":\"循环一个集合\"")
            .replaceAll("\"displayName\":\"Fork\"", "\"displayName\":\"分叉\"")
            .replaceAll("\"description\":\"Fork workflow execution into multiple branches.\"", "\"description\":\"将一个流程分叉成多个\"")
            .replaceAll("\"description\":\"Evaluate a Boolean expression and continue execution depending on the result.\"", "\"description\":\"根据条件判断流程走向\"")
            .replaceAll("\"displayName\":\"Join\"", "\"displayName\":\"合并\"")
            .replaceAll("\"description\":\"Merge workflow execution back into a single branch.\"", "\"description\":\"合并多个分支为一个\"")
            .replaceAll("\"label\":\"Mode\"", "\"label\":\"模式\"")
            .replaceAll("\"hint\":\"WaitAll:wait for all incoming activities to have executed. WaitAny:continue execution as soon as any of the incoming activity has executed.\"", "\"hint\":\"等待全部:等待所有动作都完成. 等候任意:任意动作完成就可以继续\"")
            .replaceAll("\"text\":\"WaitAll\"", "\"text\":\"等候全部\"")
            .replaceAll("\"text\":\"WaitAny\"", "\"text\":\"等候任意\"")
            .replaceAll("\"displayName\":\"Parallel for Each\"", "\"displayName\":\"并行 for Each\"")
            .replaceAll("\"description\":\"Iterate over a collection in parallel.\"", "\"description\":\"并行循环一个集合\"")
            .replaceAll("\"displayName\":\"Switch\"", "\"displayName\":\"开关\"")
            .replaceAll("\"description\":\"Evaluate multiple conditions and continue execution depending on the results.\"", "\"description\":\"评估多个条件的值，并且根据值运行\"")
            .replaceAll("\"description\":\"Execute while a given condition is true.\"", "\"description\":\"条件为真时循环\"")
            .replaceAll("\"category\":\"Compensation\"", "\"category\":\"补偿\"")
            .replaceAll("\"displayName\":\"Compensable\"", "\"displayName\":\"可补偿\"")
            .replaceAll("\"description\":\"Allow work that executed after this activity to be undone.\"", "\"description\":\"允许之后的动作被回滚\"")
            .replaceAll("\"displayName\":\"Compensate\"", "\"displayName\":\"补偿\"")
            .replaceAll("\"description\":\"Invoke a specific compensable activity.\"", "\"description\":\"运行一个可补偿的动作\"")
            .replaceAll("\"displayName\":\"Confirm", "\"displayName\":\"确认")
            .replaceAll("\"description\":\"Confirm a specific compensable activity.\"", "\"description\":\"确认一个可补偿的动作\"")
            .replaceAll("\"category\":\"Scripting\"", "\"category\":\"脚本\"")
            .replaceAll("\"displayName\":\"Run JavaScript\"", "\"displayName\":\"运行Javascript\"")
            .replaceAll("\"description\":\"Run JavaScript code.\"", "\"description\":\"运行Javascript脚本\"")
            .replaceAll("\"category\":\"Email\"", "\"category\":\"电子邮件\"")
            .replaceAll("\"displayName\":\"Composite Activity\"", "\"displayName\":\"组合动作\"");

            return rv;
        }
    </script>

    <script>
        elsaStudioRoot.addEventListener('initialized', e => {
            document.querySelector("img[alt='Workflow']").remove();
            document.querySelector("intl-message[label='Workflow Definitions']").textContent = "流程定义";
            document.querySelector("intl-message[label='Workflow Instances']").textContent = "流程实例";
            document.querySelector("intl-message[label='Workflow Registry']").remove();
        });
    </script>
</body>
</html>
